package com.tanhua.dubbo.api;

import com.tanhua.api.FriendApi;
import com.tanhua.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;


@DubboService
public class FriendApiImpl implements FriendApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void save(Long FriendId, Long getid) {
        Query query = Query.query(Criteria.where("userId").is(getid).and("friendId").is(FriendId));
        boolean exists = mongoTemplate.exists(query, Friend.class);
        if (!exists){
            Friend friend = new Friend();
            friend.setUserId(getid);
            friend.setFriendId(FriendId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
          /*  private ObjectId id;
            private Long userId; //用户id
            private Long friendId; //好友id
            private Long created; //时间*/
        }

        Query query1 = Query.query(Criteria.where("friendId").is(getid).and("userId").is(FriendId));
        boolean exists1 = mongoTemplate.exists(query1, Friend.class);
        if (!exists1){
            Friend friend = new Friend();
            friend.setUserId(FriendId);
            friend.setFriendId(getid);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
          /*  private ObjectId id;
            private Long userId; //用户id
            private Long friendId; //好友id
            private Long created; //时间*/
        }
    }

    @Override
    public List<Friend> findList(Long getid) {
        Query query = new Query(Criteria.where("userId").is(getid));
        List<Friend> friends = mongoTemplate.find(query, Friend.class);

        return friends;
    }

    @Override
    public void delete(Long userId, Long getid) {
        Query query = new Query(Criteria.where("userId").is(getid).and("friendId").is(userId));
        mongoTemplate.remove(query, Friend.class);
        Query query1 = new Query(Criteria.where("userId").is(userId).and("friendId").is(getid));
        mongoTemplate.remove(query1,Friend.class);
    }
}
